<template>
  <Spin :spinning="loading" tip="Loading...">
    <div>
      <!-- 搜索 -->
      <!-- 索赔申请 -->
      <TopFilter ref="TopFilterss" :list="topFilterInit" :cols="3" :collapse="collapse"  labelWidth="120" @filterChange="changeHandle" @resetChange="resetHandle"></TopFilter>
      <!-- table -->
      <FilterTable
        ref="table"
        :columns="columns"
        :params="fetchParams"
        :dataSource="dataList"
        :fetchapi="fetchApi"
        :datakey="'records'"
        :onColumnsChange="columns => (this.columns = columns)"
        :onRowSelectChange="selectChange"
        columnsRef="ClaimChecklgr"
        :is-select-column="false"
      >
        <template slot="controls" slot-scope="props">
<!--          <multiuse-button size="small" type="primary"  @click="batchExamine()">批量审核</multiuse-button>-->
          <!--        <multiuse-button size="small" type="primary"  @click="batchReject()">批量驳回</multiuse-button>-->
          <multiuse-button size="small" type="primary"  @click="exportFileBtn()">导出</multiuse-button>
<!--          <multiuse-button size="small" type="primary"  :loading="exportLoading" :click="downloadTemplate.bind()">下载批量驳回模板</multiuse-button>-->
<!--          <multiuse-button size="small" icon="el-icon-upload" :click="showImportFun.bind()" >导入批量驳回</multiuse-button>-->
        </template>
      </FilterTable>
      <BaseDialog :visible.sync="visible" :title="'车型选择'" destroyOnClose :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
        <ModelVehicle @close="close" @save="save"></ModelVehicle>
      </BaseDialog>
      <Drawer :visible.sync="visibleEdit" :title="'索赔审核'" destroyOnClose width="100%" :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
        <editForm @close="editclose" @save="editsave" :rowData="rowData" :editIds="editIds"></editForm>
      </Drawer>
      <!--  服务中心选择 -->
      <BaseDialog :visible.sync="selectDelearFlag" title="服务中心选择" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
        <DealerList @close="Delearclose" @save="Delearsave" selectionType="multiple" />
      </BaseDialog>
      <BaseDialog :visible.sync="showImport" icon="el-icon-upload" :closable="false" title="导入" width="800px" destroyOnClose :containerStyle="{ height: 'calc(100% - 120px)', overflow: 'auto', paddingBottom: '60px' }">
        <importExcel @close="showImport = false" @importclose="auditsave()" url="/api/cms_claimfac/rPCmsClaim/importExcel"/>
      </BaseDialog>
    </div>
  </Spin>
</template>
<script>
import { getSpList,getListForExport,backAll,downloadModel,exporturl}  from '@/api/claim/factory/ClaimQueryFactory/index';
import ModelVehicle from '@/pages/claimDemage/tools/ModelVehicle.vue';
import editForm from './editForm.vue';
import { exportExcelFile } from '@/utils/index';
import DealerList from '@/pages/claimDemage/tools/DealerList.vue';
import importExcel from '@/pages/claimDemage/tools/importExcel.vue';
import {  getAppId ,getUserOrgId} from '@/assets/js/auth';
import { dictionary } from '@/utils/dictMixin';
import { getPositionByUserOrgId,getDealerAttachListByUser } from '@/api/dictionary';
import moment from "moment";
export default {
  name:'ClaimCheck',
  mixins: [dictionary],
  components: {
    ModelVehicle,editForm,DealerList,importExcel
  },
  data() {
    return {
      // 非单个禁用
      // single: true,
      single: false,
      // 非多个禁用
      multiple: true,
      dealerList: [],
      selectDelearFlag: false,
      dealerCompanyCode: [],
      dealerData: [],
      selectDealerData: [],
      empDealerData:[],
      loading:false,
      dataList: [],
      visible: false,
      visibleDrawer: false,
      collapse: true,
      infoId: null,
      position:null,
      topFilterInit: this.topFilterInitFun(),
      flterValue: {}, //参数
      fetchApi:getSpList,
      columns: this.creatHeader(),
      fetchParams: {
        claimStatus:55131002,
        queryType:"check",
        xhrAbort: true
      }, //ipa 接口
      selectedRows: [], //选中服务中心
      dialogTitle: '选择车辆',
      visibleAdd: false,
      visibleEdit:false,
      rowData:{},
      editIds: [],
      showImport:false,
      exportLoading:false,
    };
  },
  created() {
    this.chuqi();
  },
  methods: {
    //搜索数据
    topFilterInitFun() {
      return [
        {
          type: 'SELECT',
          label: '服务中心',
          render: (p) => {
            return (
              <div>
                <el-select v-model={this.selectDealerData} disabled={true} multiple placeholder="请选择">
                  {this.dealerData.map((item) => (
                    <el-option key={item.dealerCode} label={item.dealerShortname} value={item.dealerCompanyCode} />
                  ))}
                </el-select>
                <multiuse-button style="position: absolute;right: 0;height:100%" icon="el-icon-search" onClick={() => this.selectDelearFlag = true} />
              </div>
            );
          },
          onChange: val => {
            console.log(val)
          }
          // onInput: val => {
          //   // 修改store中 经销商名
          //   setStateParam('searchDealerName', val)
          //   // 重置store中 经销商code
          //   setStateParam('searchDealerCode', null)
          // }
        },
        { type: 'INPUT', label: '服务中心名称', fieldName: 'dealerName', placeholder: '请输入', initialValue: '' },
        { type: 'INPUT', label: '索赔单号', fieldName: 'claimNo', placeholder: '请输入', initialValue: '' },
        { type: 'INPUT', label: '预授权单号', fieldName: 'authNo', placeholder: '请输入', initialValue: '' },
        { type: 'INPUT', label: '维修工单号', fieldName: 'roNo', placeholder: '请输入', initialValue: '' },
        { type: 'SELECT', label: '索赔单状态', fieldName: 'claimStatus', placeholder: '请选择', initialValue: '', itemList: this.createDictList('5513', [55131001, 55131003, 55131004, 55131005, 55131006,55131007,55131008]) },
        {
          type: 'RANGE_DATE',
          label: '提交日期',
          fieldName: 'beginSubmitAt|endSubmitAt',
          placeholder: '请输入',
          initialValue: [
            moment(new Date()).subtract(1,'months')
              .format("YYYY-MM-DD"),
            moment(new Date())
              .format("YYYY-MM-DD")
          ],
          rules: [{ required: true, message: '请选择日期', trigger: 'change' }]
        },
        { type: 'INPUT', label: '主损件名称', fieldName: 'partName', placeholder: '请输入', initialValue: '' },
        { type: 'INPUT', label: '主损件代码', fieldName: 'partCode', placeholder: '请输入', initialValue: '' },
        { type: 'SELECT', label: '索赔类型', fieldName: 'cmsClaimType', placeholder: '请选择索赔类型...', initialValue: '', filterable: true, itemList: this.createDictList('5510',[]) },
        { type: 'INPUT', label: 'VIN', fieldName: 'vin', placeholder: '请输入', initialValue: '' },

        {
          type: 'INPUT',
          label: '车型',
          fieldName: 'modelCode',
          placeholder: '请输入',
          initialValue: '',
          unitRender: p => {
            return (
              <div>
                <multiuse-button icon="el-icon-search" onClick={() => this.chooseOrderNo()} />
              </div>
            );
          }
        },
        // { type: 'SELECT', label: '动力形式', fieldName: 'ifComm', placeholder: '请选择动力形式...', initialValue: '',itemList: [] },
        // { type: 'INPUT', label: '批量活动名称', fieldName: 'batchName', placeholder: '请输入', initialValue: '' },
        // { type: 'INPUT', label: '车牌号', fieldName: 'vhlPlate', placeholder: '请输入', initialValue: '' },
        // { type: 'RANGE_DATE', label: '申请日期', fieldName: 'startTime|endTime', placeholder: '请输入', initialValue: '' },
        // { type: 'RANGE_DATE', label: '提交日期', fieldName: 'beginSubmitAt|endSubmitAt', placeholder: '请输入', initialValue: '' }
      ];
    },
    //搜索获取数据
    changeHandle(val) {
      if(!val.beginSubmitAt) {
        this.$notify.warning({ title: '提示信息', message: '提交开始日期不可为空！' });
        return
      }
      if(!val.endSubmitAt) {
        this.$notify.warning({ title: '提示信息', message: '提交结束日期不可为空！' });
        return
      }
      // if(getAppId() == 'arcfox') {
      //   if (moment(moment(val.endSubmitAt).format('YYYY-MM-DD')).diff(moment(val.beginSubmitAt), 'months', true) > 12) {
      //     this.$notify.warning({ title: '提示信息', message: '提交日期跨度不可超过十二个月！' });
      //     return
      //   }
      // } else {
        // if (moment(moment(val.endSubmitAt).format('YYYY-MM-DD')).diff(moment(val.beginSubmitAt), 'months', true) > 12) {
        //   this.$notify.warning({ title: '提示信息', message: '提交日期跨度不可超过十二个月！' });
        //   return
        // }
      // }

      val.beginSubmitAt = this.topFilterInit.find(x => x.fieldName == 'beginSubmitAt|endSubmitAt').initialValue[0];
      val.endSubmitAt = this.topFilterInit.find(x => x.fieldName == 'beginSubmitAt|endSubmitAt').initialValue[1];

      if(val.beginSubmitAt) {
        val.beginSubmitAt = moment(val.beginSubmitAt).format('YYYY-MM-DD HH:mm:ss');
      }
      if(val.endSubmitAt) {
        val.endSubmitAt = moment(val.endSubmitAt).format('YYYY-MM-DD HH:mm:ss');
      }
      this.fetchParams = Object.assign({}, this.fetchParams, val, {
        position:this.position,claimStatus:55131002,dealerCode: this.searchDealerCode, dealerCompanyCode: this.selectDealerData.length ? this.selectDealerData : null,
        empDealerData: this.empDealerData,xhrAbort: false
      });
      console.log(val);
    },
    resetHandle(val) {
      this.dealerData = [];
      this.selectDealerData = [];
      this.fetchParams = Object.assign({}, this.fetchParams, val, {position:this.position,claimStatus:55131002, dealerCompanyCode: null,empDealerData: this.empDealerData, }, { xhrAbort: false });
    },
    batchExamine() {
      if (this.selectedRows.length > 0) {
        this.selectedRows.map(x => {
          this.editIds.push({claimId: x.claimId,status: 0,roNo: x.roNo ,vin: x.vin,claimStatus:x.claimStatus});
        });
        this.visibleEdit = true;
      }else{
        return this.$notify.warning({title: '提示信息', message: '请勾选后再进行审核！'});
      }

    },
    async batchReject() {
      this.$confirm('是否确认批量驳回这些数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          let str = '';
          this.selectedRows.map(x => {
            str += x.claimId + ',';
          });
          console.log(str);
          const res = await backAll({ ids: str, status: 55131004 });
          if(res.resultCode == 200){
            this.shuaxin();
          }
        })
        .catch(() => {});
    },
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 60,
          render: props => {
            return (
              <div >
                <multiuse-button size="mini" type="text" onClick={() => this.edit(props.row)} circle> 审核</multiuse-button>
              </div>
            );
          }
        },
        { title: '服务中心代码', dataIndex: 'dealerCode', sorter: true },
        { title: '服务中心名称', dataIndex: 'dealerName', sorter: true },
        { title: '索赔单号', dataIndex: 'claimNo', sorter: true },
        { title: '索赔单状态', dataIndex: 'statusStr', sorter: true },
        { title: '索赔类型', dataIndex: 'cmsClaimTypeStr', sorter: true },
        { title: '预授权单号', dataIndex: 'authNo', sorter: true },
        { title: '维修工单号', dataIndex: 'roNo', sorter: true },
        { title: 'VIN', dataIndex: 'vin', sorter: true },
        { title: '车牌号', dataIndex: 'licenseNo', sorter: true },
        { title: '车型名称', dataIndex: 'modelName', sorter: true },
        { title: '主损件代码', dataIndex: 'partCode', sorter: true },
        { title: '主损件名称', dataIndex: 'partName', sorter: true },
        { title: '责任商代码', dataIndex: 'responsibleCode', sorter: true},
        { title: '采购渠道代码', dataIndex: 'channelCode', sorter: true},
        // { title: '供应商', dataIndex: 'supName', sorter: true},
        { title: '行驶里程', dataIndex: 'driveMile', sorter: true },
        { title: '故障现象代码', dataIndex: 'sysCode4', sorter: true },
        { title: '故障现象名称', dataIndex: 'sysName4', sorter: true },
        { title: '故障原因代码', dataIndex: 'frCode', sorter: true },
        { title: '故障原因名称', dataIndex: 'frName', sorter: true },
        // { title: '索赔金额', dataIndex: 'amount', sorter: true ,
        //   render: props => {
        //     return <span>{props.row.priceAmount==0?props.row.sumAmount:props.row.priceAmount}</span>;
        //   }},
        { title: '索赔金额', dataIndex: 'sumAmount', sorter: true ,precision: 2, numberFormat: true},
        { title: '工时费', dataIndex: 'labourAmount', sorter: true ,precision: 2, numberFormat: true},
        { title: '备件费', dataIndex: 'partAmount', sorter: true,precision: 2, numberFormat: true },
        { title: '备件管理费', dataIndex: 'partManageAmount', sorter: true },
        { title: '附加费用', dataIndex: 'addAmount', sorter: true ,precision: 2, numberFormat: true},
        { title: '外出救援费用', dataIndex: 'outAmount', sorter: true ,precision: 2, numberFormat: true},
        { title: 'PDI费用', dataIndex: 'priceAmount', sorter: true ,precision: 2, numberFormat: true},
        { title: '保修起始日期', dataIndex: 'repairBeginDate', sorter: true, dateFormat: 'yyyy-MM-dd' },
        { title: '保修截止日期', dataIndex: 'repairEndDate', sorter: true, dateFormat: 'yyyy-MM-dd' },
        { title: '生产日期', dataIndex: 'prodDate', sorter: true, dateFormat: 'yyyy-MM-dd' },
        { title: '销售日期', dataIndex: 'saleDate', sorter: true, dateFormat: 'yyyy-MM-dd' },
        { title: '维修日期', dataIndex: 'serviceBeginDate', sorter: true, dateFormat: 'yyyy-MM-dd' },
        { title: '申请人', dataIndex: 'applyName', sorter: true },
        { title: '申请时间', dataIndex: 'applyAt', sorter: true, width: 140 },
        { title: '审核人', dataIndex: 'checkBy', sorter: true },
        { title: '审核时间', dataIndex: 'checkAt', sorter: true },
      ];
    },
    async chuqi(){
      console.log("进来了")
      let res = await getPositionByUserOrgId(getUserOrgId());
      if (res.resultCode == 200) {
        this.position = res.data;
        if( this.position==10991001){
          let params={appId:getAppId()};
          let deaRes = await getDealerAttachListByUser(params);
          if (deaRes.resultCode == 200) {
            this.dealerCodes = deaRes.data.records;
            this.empDealerData = [];
            this.dealerCodes.forEach(item => {
              this.empDealerData.push(item.dealerCompanyCode);
            });
          }
        }
      }

    },
    //选中
    selectChange(rows) {
      this.selectedRows = rows;
      console.log(this.selectedRows);
    },
    close() {
      this.visible = false;
    },
    chooseOrderNo() {
      this.visible = true;
    },
    chooseDealerNo() {
      this.visibleAdd = true;
    },
    //服务中心选择页面
    SelectDelear() {
      this.selectDelearFlag = true;
    }, //关闭
    Delearclose() {
      this.selectDelearFlag = false;
    },
    //服务中心选择保存
    Delearsave(obj) {
      console.log('选择数据传递', obj);
      this.dealerData = obj;
      this.selectDealerData = [];
      obj.forEach(item => {
        this.selectDealerData.push(item.dealerCompanyCode);
      });
      this.selectDelearFlag = false;
    },
    save(obj) {
      this.topFilterInit.find(x => x.fieldName == 'modelCode').initialValue = obj[0].modelCode;
      this.visible = false;
    },
    async exportFileBtn() {
      // let json = Object.assign({}, { CODE: 'CODE_00000139' }, this.fetchParams);
      // let res = await exporturl(json);
      // if (res.resultCode == 200) {
      //   this.$router.push('/admin/auth/oem/downloadCenter');
      // }
      let beginSubmitAt = this.topFilterInit.find(x => x.fieldName == "beginSubmitAt|endSubmitAt").initialValue[0];
      let endSubmitAt = this.topFilterInit.find(x => x.fieldName == "beginSubmitAt|endSubmitAt").initialValue[1];
      if(!beginSubmitAt) {
        this.$notify.warning({ title: '提示信息', message: '提交开始日期不可为空！' });
        return
      }
      if(!endSubmitAt) {
        this.$notify.warning({ title: '提示信息', message: '提交结束日期不可为空！' });
        return
      }
      if(getAppId() == 'arcfox') {
        if (moment(moment(endSubmitAt).format('YYYY-MM-DD')).diff(moment(beginSubmitAt), 'months', true) > 12) {
          this.$notify.warning({ title: '提示信息', message: '提交日期跨度不可超过十二个月！' });
          return
        }
      } else {
        if (moment(moment(endSubmitAt).format('YYYY-MM-DD')).diff(moment(beginSubmitAt), 'months', true) > 12) {
          this.$notify.warning({ title: '提示信息', message: '提交日期跨度不可超过十二个月！' });
          return
        }
      }
      let obj = Object.assign({}, this.fetchParams, {position:this.position,claimStatus:55131002,dealerCode: this.searchDealerCode, dealerCompanyCode: this.selectDealerData.length ? this.selectDealerData : null,
        empDealerData: this.empDealerData,xhrAbort: false});
      obj.beginSubmitAt = this.topFilterInit.find(x => x.fieldName == 'beginSubmitAt|endSubmitAt').initialValue[0];
      obj.endSubmitAt = this.topFilterInit.find(x => x.fieldName == 'beginSubmitAt|endSubmitAt').initialValue[1];
      if(obj.beginSubmitAt) {
        obj.beginSubmitAt = moment(obj.beginSubmitAt).format('YYYY-MM-DD HH:mm:ss');
      }
      if(obj.endSubmitAt) {
        obj.endSubmitAt =  moment(obj.endSubmitAt).format('YYYY-MM-DD HH:mm:ss');
      }
      this.loading =true;
      getListForExport(obj).then(res => {
        exportExcelFile(res.data, '索赔单信息');
        this.loading =false;
      });
    },
    add() {
      this.visibleAdd = true;
    },
    shuaxin () {
      this.fetchParams = { ...this.fetchParams };
    },
    // saveAdd() {
    //   this.visibleAdd = false;
    //   this.fetchParams = { ...this.fetchParams };
    // },
    editclose() {
      this.visibleEdit = false;
    }, edit(val) {
      this.rowData = val;
      this.editIds=[];
      this.visibleEdit = true;
    },
    auditsave() {
      this.showImport = false;
      this.fetchParams = {...this.fetchParams};
    },
    editsave() {
      this.visibleEdit = false;
      this.fetchParams = { ...this.fetchParams };
    },   //下载模板
    downloadTemplate() {
      this.$confirm('此操作将下载excel模板, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.exportLoading = true;
        downloadModel().then(res => {
          console.log('666');
          console.log(res);
          exportExcelFile(res.data, '批量驳回导入模板');
          this.exportLoading = false;
        });
      });
    },
    // Excel更新导入
    showImportFun() {
      this.showImport = true;
    },
  }
  // mounted() {
  //   this.BaseTable = this.$refs.listModal.$refs.pageTable;
  // }
};
</script>

<style lang="less" scoped></style>
